package com.cwx.mychat.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.cwx.mychat.entity.constant.CodeConstant;
import com.cwx.mychat.entity.po.UserInfo;
import com.cwx.mychat.service.UserInfoService;
import com.cwx.mychat.utils.PageUtils;
import com.cwx.mychat.utils.Query;
import com.cwx.mychat.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Map;

public abstract class BaseController<S extends IService<M>, M> {

    private Class<M> entityClass;

    protected BaseController(){
        Type genericSuperclass = getClass().getGenericSuperclass();
        if(genericSuperclass instanceof ParameterizedType){
            ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
            entityClass = (Class<M>)parameterizedType.getActualTypeArguments()[1];
        }
    }


    @Autowired
    protected S service;

    /**
     * 基础分页信息查询
     * @param params
     * @return
     */
    @GetMapping("/baseList")
    protected PageUtils baseList(@RequestParam Map<String, Object> params){
        IPage<M> page = service.page(
                new Query<M>().getPage(params),
                new QueryWrapper<M>()
        );
        return new PageUtils(page);
    }


    /**
     * 基础信息查询ById
     */
    @RequestMapping("/baseInfo/{id}")
    public R info(@PathVariable("id") Long id){
        M entity = service.getById(id);
        return R.ok().put(CodeConstant.RESULT_MSG, entity);
    }

    /**
     * 基础新增
     * @return
     */
    @PostMapping("/baseSave")
    protected R baseSave(@RequestBody M entity){
        service.save(entity);
        return R.ok();
    }

    /**
     * 基础修改
     * @param entity
     * @return
     */
    @PutMapping("/baseUpdate")
    protected R baseUpdate(@RequestBody M entity){
        service.updateById(entity);
        return R.ok();
    }

    /**
     * 基础删除
     * @param ids
     * @return
     */
    @DeleteMapping("/baseMove")
    protected R baseDelete(@RequestBody Long[] ids){
        service.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

}
